import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Row, Col, Button, Radio, Upload, Tabs, message } from 'antd';
import React, { useState, useEffect } from 'react';

import {
  Const
} from '../../Const';
import { upload } from '../service';

class PrivateData {
  static layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 20,
    },
  };
  static imgType = new Map()
    .set(1, 'poSunImgListMap')
    .set(2, 'shaoShouImgListMap')
    .set(3, 'duoShouImgListMap')
    .set(6, 'neiWuQueShiImgListMap')
    .set(7, 'poSunImgListMap')
    .set(10, 'kuaiDiWuPinImgListMap');
  static showLostItemPicMap = new Map()
    .set(1, 'goodFileList')
    .set(2, 'touristFileList')
    .set(3, 'paperFileList')
    .set(4, 'luggageFileList');
  static imgObj = {};
}

const PicUpload = props => {

  const { lostItemPicVisible, form, onCancel, onSubmit: handleImgs, ownerType, lostItemPic } = props;

  // 图片大类
  const [picCategoryOptions, setPicCategoryOptions] = useState([]);
  // 图片小类
  const [picTypeOptions, handlePicTypeOptions] = useState([]);
  // 上传文件
  const [fileList, updateFileList] = useState([]);
  const [fileListInfo, handleFileListInfo] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });

  useEffect(() => {
    if (lostItemPicVisible) {
      handleFileListInfo(lostItemPic);
      PrivateData.imgObj = Const[PrivateData.imgType.get(ownerType)];
      let _picCategoryOptions = [];
      let _picTypeOptions = [];
      for (let key in PrivateData.imgObj) {
        _picCategoryOptions.push({
          value: key,
          label: PrivateData.imgObj[key].text
        });
      }
      let imgChildrenObj = PrivateData.imgObj[_picCategoryOptions[0].value].children;
      for (let key in imgChildrenObj) {
        _picTypeOptions.push({
          value: key,
          label: imgChildrenObj[key]
        })
      }
      setPicCategoryOptions(_picCategoryOptions);
      handlePicTypeOptions(_picTypeOptions);
      setTimeout(() => {
        form.setFieldsValue({
          picCategory: _picCategoryOptions[0].value,
          picType: _picTypeOptions[0].value,
        })
      }, 0);
    } else {
      PrivateData.imgObj = {};
    }
  }, [lostItemPicVisible, ownerType, lostItemPic])

  // 上传配置
  const uploadProps = {
    fileList,
    headers: {
      authorization: localStorage.getItem('authorization') || ''
    },
    onRemove: file => {
      let goodFileList = fileListInfo.goodFileList || []
      let touristFileList = fileListInfo.touristFileList || []
      let paperFileList = fileListInfo.paperFileList || []
      let luggageFileList = fileListInfo.luggageFileList || []

      let goodFileListData = goodFileList.filter(item => {
        return item?.file?.uid !== file.uid
      })

      let touristFileListData = touristFileList.filter(item => {
        return item?.file?.uid !== file.uid
      })

      let paperFileListData = paperFileList.filter(item => {
        return item?.file?.uid !== file.uid
      })

      let luggageFileListData = luggageFileList.filter(item => {
        return item?.file?.uid !== file.uid
      })

      handleFileListInfo({
        ...fileListInfo,
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData
      });
    },
    beforeUpload: file => {
      if (fileListInfo.goodFileList.length + fileListInfo.touristFileList.length + fileListInfo.paperFileList.length + fileListInfo.luggageFileList.length >= 9) {
        message.error('最多上传9张图片')
        return false
      } else {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 20;

        if (!isJPG && !isPNG) {
          message.warning(`请选择正确图片格式`)
        }
        if (!isLt2M) {
          message.warning(`请选择20MB以下的图片`)
        }
        return (isJPG || isPNG) && isLt2M
      }
    },
    onChange: info => {
      updateFileList(info.fileList.filter(file => !!file.status));
      if (info?.file?.status === 'done') {
        let picCategory = +form.getFieldsValue().picCategory;
        let picType = +form.getFieldsValue().picType;
        let strName = PrivateData.showLostItemPicMap.get(picCategory);
        handleFileListInfo({
          ...fileListInfo,
          [strName]: [
            ...fileListInfo[strName],
            {
              file: info?.file?.originFileObj,
              imgUrl: info?.file?.response?.data[0],
              oneType: picCategory,
              twoType: picType
            }
          ],
        });
        message.success('上传成功');
      }
    },
    onPreview: file => {
      return false;
    }
  };

  // 切换图片大类更换小类
  const changePicType = (e) => {
    let val = e.target.value;
    let _picTypeOptions = [];
    let imgChildrenObj = PrivateData.imgObj[val].children;
    for (let key in imgChildrenObj) {
      _picTypeOptions.push({
        value: key,
        label: imgChildrenObj[key]
      })
    }
    handlePicTypeOptions(_picTypeOptions);
    form.setFieldsValue({
      picType: ''
    });
  }

  // 确认
  const okHandle = () => {
    let isHaveData = false;
    for (let key in fileListInfo) {
      if (fileListInfo[key] && fileListInfo[key].length !== 0) {
        isHaveData = true;
        break;
      }
    }
    if (isHaveData) {
      handleImgs(fileListInfo);
    } else {
      message.warning('图片不能为空');
    }
  };

  return (
    <Modal
      title={[
        <div key="title">图片上传</div>
      ]}
      width="700px"
      visible={lostItemPicVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <div>
        <Form.Item
          {...PrivateData.layout}
          label='图片大类'
          labelAlign='left'
        >
          {form.getFieldDecorator('picCategory', {
            initialValue: 1
          })(
            <Radio.Group onChange={(e) => changePicType(e)}>
              {
                picCategoryOptions.map(item => (
                  <Radio.Button value={item.value}>{item.label}</Radio.Button>
                ))
              }
            </Radio.Group>
          )}
        </Form.Item>
        <Form.Item
          {...PrivateData.layout}
          label='图片小类'
          labelAlign='left'
        >
          {form.getFieldDecorator('picType')(
            <Radio.Group>
            {
              picTypeOptions.map(item => (
                <Radio.Button value={item.value}>{item.label}</Radio.Button>
              ))
            }
          </Radio.Group>
          )}
        </Form.Item>
        <Upload action={'/api/uploadAndDownload/upload'} listType="picture" {...uploadProps}>
          <Button type="primary" disabled={!form.getFieldsValue().picType}>选择图片</Button>
        </Upload>
      </div>
    </Modal>
  );
};

export default Form.create()(PicUpload);
